<template>
  <div class="pages logins">
    <div class="logo"><img :src="logo" alt=""></div>
    <div class="loginWrap">
      <template v-if='!fixPassword && !register'>
        <div class="titleTbox">
          <p class="titleT">商户平台</p>
          <p class="titleM">
            <span :class="(price===1)?'active':''" @click="tabSwitch(1,'signIn')" class="buttonT">验证码登录</span>
            <span class="active">|</span>
            <span :class="(price===2)?'active':''" @click="tabSwitch(2,'signIn')" class="buttonT">密码登录</span>
          </p>

        </div>
        <el-form key='1' :model="signIn" :rules='signInRules' ref="signIn" label-position="right" label-width="20px" class="login-container">
          <el-form-item prop='userName'>
            <el-input type="phone" v-model="signIn.userName" prefix-icon="el-icon-phone" placeholder="请输入手机号" maxlength='11' @keyup.native='replace(signIn.userName,signIn,"userName")' clearable></el-input>
          </el-form-item>
          <el-form-item prop='password' v-if="price==2">
            <el-input type="password" v-model="signIn.password" prefix-icon="el-icon-edit" placeholder="请输入密码" onpaste="return false" oncontextmenu="return false" maxlength='20' oncopy="return false" oncut="return false" clearable @keyup.enter.native='signInBtn("signIn")'></el-input>
          </el-form-item>
          <!-- <el-form-item prop='userName'>
            <el-input type="phone" v-model="signIn.userName" prefix-icon="el-icon-printer" placeholder="请输入验证码" maxlength='11' @keyup.native='replace(signIn.userName,signIn,"userName")' clearable></el-input>
          </el-form-item> -->
          <!-- 创建密码框 触发浏览器记住密码功能 -->
          <input type="password" v-if="price==1" style="width:0;height:0;float:left;opacity:0">
          <el-form-item prop="Code" v-if="price==1">
            <el-row>
              <el-col :span="12">
                <el-input type="Code" placeholder="验证码" size="small" maxlength="6" v-model="signIn.Code" oninput="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')" @keyup.enter.native='signInBtn("signIn")'></el-input>
              </el-col>
              <el-col :span="12">
                <div class="clickCode">
                  <el-button style="font-size:14px;margin-left: 50px;" v-if="codeMsg!='获取验证码'">{{countdowns+codeMsg}}</el-button>
                  <el-button type="primary" @click="getCode()" style="font-size:14px;margin-left:50px;" v-if="codeMsg=='获取验证码'">{{countdowns+codeMsg}}</el-button>
                </div>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="width:100%;" class="loginBox" v-text="'登录'" @click='signInBtn("signIn")'></el-button>
          </el-form-item>
          <div class='btn-bottom'>
            <div class='register' @click.stop='goRegister()'>注册</div>
            <div class="forgetPassword" @click="forgetPassword()">忘记密码</div>
          </div>
        </el-form>
      </template>
      <template v-else-if='fixPassword'>
        <div class="titleTbox">
          <p class="titleT">商户平台</p>
          <p class="title">
            <i class="el-icon-minus"></i>&nbsp;修改密码&nbsp;
            <i class="el-icon-minus"></i>
          </p>
        </div>
        <el-form key='2' :model="forget" :rules='forgetRules' ref="forget" label-position="right" label-width="20px" class="forget-container">
          <el-form-item prop='mobile'>
            <el-input type="phone" autocomplete='off' v-model="forget.mobile" prefix-icon="el-icon-phone" placeholder="请输入手机号" maxlength='11' @keyup.native='replace(forget.mobile,forget,"mobile")' clearable></el-input>
          </el-form-item>
          <div class='validateCode-wrap'>
            <el-form-item prop='validateCode' style='width:60%'>
              <el-input type="validateCode" v-model="forget.validateCode" prefix-icon="el-icon-edit" placeholder="请输入验证码" maxlength='6' @keyup.native='replace(forget.validateCode,forget,"validateCode")' clearable></el-input>
            </el-form-item>
            <el-form-item style='width:40%'>
              <el-button style='width:100%;' type="primary" class="loginBox" @click="getValidateCode()" :disabled='yzmstatus'>{{countdown}}</el-button>
            </el-form-item>
          </div>
          <input type="text" style="height:0px;float:left;opacity:0">
          <el-form-item prop='password'>
            <!-- forget.password -->
            <el-input type="password" autocomplete="new-password" v-model="forget.password" prefix-icon="el-icon-edit" placeholder="请输入新密码" onpaste="return false" oncontextmenu="return false" maxlength='20' oncopy="return false" oncut="return false" clearable></el-input>
          </el-form-item>
          <el-form-item prop='password2'>
            <el-input type="password" autocomplete="new-password" v-model="forget.password2" prefix-icon="el-icon-edit" placeholder="请再次输入新密码" onpaste="return false" oncontextmenu="return false" maxlength='20' oncopy="return false" oncut="return false" clearable @keyup.enter.native='resetPassword()'></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="width:100%;" class="loginBox" @click="resetPassword()" v-text="'重置密码'"></el-button>
          </el-form-item>
          <div class="forgetPassword" @click="goSign()">返回登录</div>
        </el-form>
      </template>
      <template v-else>
        <div class="titleTbox">
          <p class="titleT">商户平台</p>
          <p class="title">
            <i class="el-icon-minus"></i>&nbsp;注册&nbsp;
            <i class="el-icon-minus"></i>
          </p>
        </div>
        <el-form key='3' :model="registerData" ref="registerData" :rules='registerRules' label-position="right" label-width="20px" class="login-container">
          <!--              <el-form-item prop='userName'>-->
          <!--                <el-input type="text" v-model="registerData.userName" prefix-icon="el-icon-news" placeholder="请输入用户名"-->
          <!--                          @keyup.native='replace(registerData.userName,registerData,"userName")' clearable></el-input>-->
          <!--              </el-form-item>-->
          <el-form-item prop='mobile'>
            <el-input type="phone" v-model="registerData.mobile" prefix-icon="el-icon-printer" placeholder="请输入手机号" maxlength='11' clearable></el-input>
          </el-form-item>
          <el-form-item prop='password'>
            <el-input type="password" v-model="registerData.password" prefix-icon="el-icon-edit" placeholder="请输入密码" onpaste="return false" oncontextmenu="return false" maxlength='20' oncopy="return false" oncut="return false" clearable></el-input>
          </el-form-item>
          <el-form-item prop='password2'>
            <el-input type="password" v-model="registerData.password2" prefix-icon="el-icon-edit" placeholder="请再次输入密码" onpaste="return false" oncontextmenu="return false" maxlength='20' oncopy="return false" oncut="return false" clearable @keyup.enter.native='registerBtn()'></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="width:100%;" class="loginBox" @click="registerBtn()" v-text="'注册'"></el-button>
          </el-form-item>
          <div class="forgetPassword" @click="goSign()">返回登录</div>
        </el-form>
      </template>
    </div>
  </div>
</template>
<script>
import logo from "assets/images/log_logo.png";
import md5 from "js-md5";
import {
  userRegister,
  userLogin,
  updPwdByCode,
  findUserSubMerchant,
  validateCode
} from "@/api";
import Cookies from "js-cookie";
import util from "@/util";
export default {
  data() {
    const checkMobile = (rule, value, callback) => {
      if (!util.validMobilePhone(value)) {
        return callback(new Error("手机号格式不正确 "));
      } else {
        callback();
      }
    };
    const checkPassword = (rule, value, callback) => {
      if (util.validChinese(value)) {
        return callback(new Error("密码不能包含中文"));
      } else if (util.validEmpty(value)) {
        return callback(new Error("密码不能包含空格！"));
      } else {
        callback();
      }
    };
    const checkPassword2 = (rule, value, callback) => {
      if (util.validChinese(value)) {
        return callback(new Error("密码不能包含中文"));
      } else if (util.validEmpty(value)) {
        return callback(new Error("密码不能包含空格！"));
      } else if (value != this.registerData.password) {
        return callback(new Error("两次密码输入不一致"));
      } else {
        callback();
      }
    };
    const fixPassword2 = (rule, value, callback) => {
      if (util.validChinese(value)) {
        return callback(new Error("密码不能包含中文"));
      } else if (util.validEmpty(value)) {
        return callback(new Error("密码不能包含空格！"));
      } else if (value != this.forget.password) {
        return callback(new Error("两次密码输入不一致"));
      } else {
        callback();
      }
    };
    return {
      price: 1,
      logo: logo,
      timer: "",
      mobile: "",
      signIn: {
        userName: "",
        password: "",
        Code: ""
      },
      codeDisabled: false, // 是否禁用按钮
      countdow: 60, //60秒
      countdowns: "", //验证码秒数
      timers: null, // 定时器
      codeMsg: "获取验证码", //按钮上的文字
      forget: {
        mobile: "",
        password: "",
        password2: "",
        validateCode: ""
      },
      registerData: {
        userName: "",
        mobile: "",
        password: "",
        password2: ""
      },
      signInRules: {
        userName: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: checkPassword, trigger: "blur" },
          { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
        ],
        Code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { min: 6, max: 6, message: "请输入6位验证码", trigger: "blur" }
        ]
      },
      registerRules: {
        // userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: checkPassword, trigger: "blur" },
          { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
        ],
        password2: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          { validator: checkPassword2, trigger: "blur" },
          { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
        ]
      },
      forgetRules: {
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ],
        validateCode: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { min: 6, max: 6, message: "请输入6位验证码", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: checkPassword, trigger: "blur" },
          { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
        ],
        password2: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          { validator: fixPassword2, trigger: "blur" },
          { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
        ]
      },
      fixPassword: false,
      register: false,
      yzmstatus: false,
      countdown: "获取验证码"
    };
  },
  mounted() {},
  methods: {
    checkMobile(s) {
      var length = s.length;
      if (length == 11 && /^1[3|4|5|7|8][0-9]\d{4,8}$/.test(s)) {
        return true;
      } else {
        return false;
      }
    },
    getCode() {
      if (
        this.signIn.userName !== "" &&
        this.checkMobile(this.signIn.userName)
      ) {
        let Data = {
          mobile: this.signIn.userName,
          type: 3
        };
        validateCode(Data).then(res => {
          if (res.code == "200") {
            this.$message({
              message: "已发送短信",
              type: "success",
              center: true,
              duration: "1000"
            });
            // this.trading = res.data.bizSerialNumber;
            // 验证码120秒倒计时;
            if (!this.timers) {
              this.timers = setInterval(() => {
                if (this.countdow > 0 && this.countdow <= 60) {
                  this.countdow--;
                  if (this.countdow !== 0) {
                    this.codeMsg = "" + "重新获取";
                    this.countdowns = this.countdow + "S";
                  } else {
                    clearInterval(this.timers);
                    this.codeMsg = "获取验证码";
                    this.countdowns = "";
                    this.countdow = 30;
                    this.timers = null;
                    this.codeDisabled = false;
                  }
                }
              }, 1000);
            }
          } else {
            this.$message({
              message: res.data.msg,
              center: true,
              duration: "1000"
            });
          }
        });
      } else {
        this.$message({
          message: "请输入正确的手机号",
          duration: "1000"
        });
      }
    },
    tabSwitch(value, ref) {
      this.price = value;
      this.$refs[ref].resetFields();
    },
    replace(value, obj, key) {
      let res = "";
      switch (key) {
        case "validateCode":
        case "mobile":
        case "userName":
          res = util.replaceNumber(value);
          break;
      }
      this.$set(obj, key, res);
    },
    getValidateCode() {
      let that = this;
      if (!that.forget.mobile) {
        that.toast("请输入手机号!", "error");
        return;
      }
      validateCode({
        mobile: that.forget.mobile
      }).then(res => {
        if (res.code == 200) {
          that.countDown();
          that.toast("验证码已发送！", "success");
        } else {
          that.toast(res.msg, "error");
        }
      });
    },
    forgetPassword() {
      this.fixPassword = true;
      this.signIn.userName = "";
      this.signIn.password = "";
      this.$refs.signIn.resetFields();
    },
    goSign() {
      if (this.register) {
        this.register = false;
        this.registerData.mobile = "";
        this.registerData.password = "";
        this.registerData.password2 = "";
        this.registerData.userName = "";
        this.$refs.registerData.resetFields();
        return;
      }
      this.fixPassword = false;
      this.forget.mobile = "";
      this.forget.password = "";
      this.forget.password2 = "";
      this.$refs.forget.resetFields();
    },
    goRegister() {
      this.fixPassword = false;
      this.register = true;
    },
    signInBtn(ref) {
      let that = this;
      this.$refs[ref].validate(valid => {
        if (valid) {
          var code = "",
            passwordd = "";
          if (that.price == 1) {
            code = 1;
            passwordd = that.signIn.Code;
          } else {
            code = "";
            passwordd = md5(that.signIn.password);
          }
          let data = {
            userName: that.signIn.userName,
            password: passwordd,
            type: code
          };
          userLogin(data).then(res => {
            if (+res.code == 200) {
              that.toast("登录成功!", "success");
              this.mobile = res.data.mobile;
              Cookies.set(
                process.env.COOKIE_NAME + "_isFirstLogin",
                res.data.isFirstLogin
              );
              that.getMerchants(res.data.token, res.data.userId);
              let userInfo = {
                headUrl: res.data.headUrl,
                mobile: res.data.mobile,
                userId: res.data.userId,
                userName: res.data.userName
              };
              Cookies.set(
                process.env.COOKIE_NAME + "_userInfo",
                JSON.stringify(userInfo)
              );
              var now = new Date();
              var time = now.getTime() + 1000*60*30;
              Cookies.set(process.env.COOKIE_NAME + "_token", res.data.token,{ expires:new Date(time) });
              that.$store.commit("SET_TOKEN", res.data.token);
            }
          });
        } else {
          return false;
        }
      });
    },
    registerBtn() {
      let that = this;
      this.$refs.registerData.validate(valid => {
        if (valid) {
          let data = {
            userName: that.registerData.userName,
            mobile: that.registerData.mobile,
            password: md5(that.registerData.password2)
          };
          userRegister(data).then(res => {
            var data = res;
            if (data.code == 200) {
              that.toast("注册成功!", "success");
              that.signIn.userName = that.registerData.mobile;
              that.signIn.password = that.registerData.password2;
              that.register = false;
            } else {
              that.toast(data.msg, "error");
            }
          });

          /*this.$message({
             message: '资料已修改！',
             type: 'success'
           });
           this.$refs.formData.resetFields();*/
        } else {
          return false;
        }
      });
    },
    resetPassword() {
      let that = this;
      this.$refs.forget.validate(valid => {
        if (valid) {
          let data = {
            mobile: that.forget.mobile,
            password: md5(that.forget.password2),
            validateCode: that.forget.validateCode
          };
          updPwdByCode(data).then(res => {
            if (+res.code == 200) {
              that.toast("密码修改成功!", "success");
              that.signIn.userName = that.forget.mobile;
              that.signIn.password = that.forget.password2;
              that.fixPassword = false;
              this.$refs.forget.resetFields();
              clearTimeout(that.timer);
              that.yzmstatus = false;
              that.countdown = "获取验证码";
            }
          });
        }
      });
    },
    getMerchants(token, userId) {
      let data = {
        token: token,
        userId: userId,
        phone: this.mobile
      };
      findUserSubMerchant(data).then(res => {
        if (+res.code == 200) {
          if (res.data.merchantList.length > 0) {
            this.$store.commit("SET_ISENTRY", true);
            window.merchantList = res.data.merchantList
            // 不管几个商户都去选择界面
            util.routerReplace("/home/select-model");
          } else {
            this.$store.commit("SET_ISENTRY", false);
            util.routerReplace("/application/entry-application");
          }
        }
      });
    },
    countDown() {
      var num = 60;
      let that = this;
      clearTimeout(that.timer);
      that.yzmstatus = true;

      function count() {
        that.countdown = num + "s";
        num = parseInt(num) - 1;
        if (num < 0) {
          that.yzmstatus = false;
          that.countdown = "获取验证码";
        } else {
          that.timer = setTimeout(function() {
            count();
          }, 1000);
        }
      }
      count();
    },
    toast(msg, type) {
      this.$message({
        message: msg,
        type: type
      });
    }
  }
};
</script>
<style lang="less" scoped>
.active {
  color: #535353;
}
.logins {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: auto;
  background-image: url("../../assets/images/logo-2.png");
  background-size: 100% 100%;
  .logo {
    width: 260px;
    height: 120px;
    position: absolute;
    left: 300px;
    background-color: #fff;
    text-align: center;
    line-height: 150px;
  }
  .loginWrap {
    width: 360px;
    position: absolute;
    top: 200px;
    right: 200px;
    padding: 35px 35px 35px 25px;
    border: 1px solid #eaeaea;
    box-shadow: 0 0 25px #cac6c6;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    background-clip: padding-box;
    background: #fff;
    .titleTbox {
      width: 100%;
      height: 100%;
      color: #535353;
      margin-bottom: 10px;
      .titleT {
        width: 100%;
        letter-spacing: 2px;
        font-size: 32px;
        text-align: center;
        margin-top: -10px;
      }
      .title {
        margin: 20px auto;
        text-align: center;
        color: #7e7e7e;
        font-size: 20px;
        font-family: MicrosoftYaHei;
      }
      .titleM {
        width: 100%;
        letter-spacing: 2px;
        font-size: 14px;
        margin: 27px auto;
        margin-left: 20px;
        color: #c0c4cc;
        text-align: left;
      }
      .buttonT {
        cursor: pointer;
      }
    }
    .btn-bottom {
      color: #999;
      margin-bottom: 20px;
      font-size: 12px;
      display: flex;
      display: -webkit-flex;
      justify-content: space-between;
      padding-left: 20px;
      & div {
        cursor: pointer;
      }
    }
    .forgetPassword {
      color: #999;
      float: right;
      margin-bottom: 20px;
      font-size: 12px;
      cursor: pointer;
    }
    .validateCode-wrap {
      display: flex;
      display: -webkit-flex;
      justify-content: space-between;
    }
  }
}
</style>
